﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.Departments;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.Departs;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.Departs
{
    /// <summary>
    /// 部门查询命令处理方法方法
    /// </summary>
    public class DepartQueryCommandHandler:IRequestHandler<DepartQueryCommand,APIResult<List<DepartDtos>>>
    {
        /// <summary>
        /// 部门仓储接口
        /// </summary>
        private readonly IBaseRepository<DepartModel> dRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="dRepo"></param>
        public DepartQueryCommandHandler(IBaseRepository<DepartModel>dRepo,IMapper mapper)
        {
            this.dRepo = dRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public  Task<APIResult<List<DepartDtos>>> Handle(DepartQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<DepartDtos>> result = new APIResult<List<DepartDtos>>();
            var list = from a in dRepo.GetAll().Result
                       join b in dRepo.GetAll().Result on a.DepartPId equals b.DepartId
                       select new DepartDtos
                       {
                           DepartId = a.DepartId,
                           DepartName = a.DepartName,
                           DepartPId = a.DepartPId,
                           DepartPIdName = b.DepartName
                       };
            if(!string.IsNullOrEmpty(request.DepartName))
            {
                list = list.Where(x=>x.DepartName.Contains(request.DepartName));
            }
            list = list.OrderByDescending(x => x.DepartId);    
            result.data = list.ToList();
            result.Msg = APIEnum.查询成功.ToString();
            result.Code = APIEnum.成功;
            result.Count = list.Count();
            return  Task.FromResult(result);




        }




    }



}
